Skip to content

Latest commit

 

History

History
79 lines (62 loc) · 1.58 KB

File metadata and controls

79 lines (62 loc) · 1.58 KB

19. Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. 

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

Solutions (Python)

1. Solution

# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution: defremoveNthFromEnd(self, head: ListNode, n: int) ->ListNode: dummy=ListNode(0) dummy.next=headnode0=headnode1=dummyfor_inrange(n): node0=node0.nextwhilenode0: node0=node0.nextnode1=node1.nextnode1.next=node1.next.nextreturndummy.next

Solutions (Ruby)

1. Solution

# Definition for singly-linked list.# class ListNode# attr_accessor :val, :next# def initialize(val = 0, _next = nil)# @val = val# @next = _next# end# end# @param {ListNode} head# @param {Integer} n# @return {ListNode}defremove_nth_from_end(head,n)dummy=ListNode.new(0,head)node0=headnode1=dummyfor_in0...nnode0=node0.nextendwhilenode0node0=node0.nextnode1=node1.nextendnode1.next=node1.next.nextreturndummy.nextend
close